import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import prisma from '@/lib/db';

export async function PATCH(request: NextRequest) {
  try {
    const session = await auth();
    
    // 检查用户是否已登录
    if (!session?.user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const userId = session.user.id;
    const data = await request.json();
    
    // 验证数据
    const validFields = ['emailNotifications', 'pushNotifications', 'weeklyDigest'];
    const validData = Object.keys(data)
      .filter(key => validFields.includes(key))
      .reduce((obj, key) => {
        obj[key] = data[key];
        return obj;
      }, {} as Record<string, any>);

    // 确保至少有一个有效字段
    if (Object.keys(validData).length === 0) {
      return NextResponse.json(
        { error: '缺少有效参数' },
        { status: 400 }
      );
    }

    // 更新用户通知设置
    const updatedSettings = await prisma.userSettings.upsert({
      where: { userId },
      update: validData,
      create: {
        userId,
        ...validData,
        // 设置默认值
        theme: 'system',
        themeColor: 'blue',
        language: 'zh_CN',
        emailNotifications: validData.emailNotifications !== undefined ? validData.emailNotifications : true,
        pushNotifications: validData.pushNotifications !== undefined ? validData.pushNotifications : true,
        weeklyDigest: validData.weeklyDigest !== undefined ? validData.weeklyDigest : true,
      }
    });

    return NextResponse.json({
      success: true,
      data: updatedSettings,
      message: '通知设置已更新'
    });
  } catch (error) {
    console.error('更新通知设置失败:', error);
    return NextResponse.json(
      { error: '更新通知设置失败' },
      { status: 500 }
    );
  }
}

export async function PUT(request: NextRequest) {
  try {
    const session = await auth();
    
    // 检查用户是否已登录
    if (!session?.user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const userId = session.user.id;
    const data = await request.json();
    
    // 验证数据
    const validFields = ['emailNotifications', 'pushNotifications', 'weeklyDigest'];
    const validData = Object.keys(data)
      .filter(key => validFields.includes(key))
      .reduce((obj, key) => {
        obj[key] = data[key];
        return obj;
      }, {} as Record<string, any>);

    // 确保至少有一个有效字段
    if (Object.keys(validData).length === 0) {
      return NextResponse.json(
        { error: '缺少有效参数' },
        { status: 400 }
      );
    }

    // 更新用户通知设置
    const updatedSettings = await prisma.userSettings.upsert({
      where: { userId },
      update: validData,
      create: {
        userId,
        ...validData,
        // 设置默认值
        theme: 'system',
        themeColor: 'blue',
        language: 'zh_CN',
        emailNotifications: validData.emailNotifications !== undefined ? validData.emailNotifications : true,
        pushNotifications: validData.pushNotifications !== undefined ? validData.pushNotifications : true,
        weeklyDigest: validData.weeklyDigest !== undefined ? validData.weeklyDigest : true,
      }
    });

    return NextResponse.json({
      success: true,
      data: updatedSettings,
      message: '通知设置已更新'
    });
  } catch (error) {
    console.error('更新通知设置失败:', error);
    return NextResponse.json(
      { error: '更新通知设置失败' },
      { status: 500 }
    );
  }
} 